package com.zyk.leetcode;

/**
 * @author zhangsan
 * @date 2021/4/4 16:09
 */
public class J15 {

    /**
     * https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/
     */
    public static int hammingWeight(int n) {
        int ans = 0;
        for (int i = 0; i < 32; i++) {
            if ((n & (1 << i)) != 0) {
                ans++;
            }
        }
        return ans;
    }

    public static int hammingWeight2(int n) {
        // n & (n-1) , 消除掉最后一个1
        // n = 那个结果. 循环做就消除完1 最后 = 0 结束循环
        int res = 0;
        while (n != 0) {
            res++;
            n &= n - 1;
        }
        return res;
    }


    // for test
    public static void main(String[] args) {
        for (int i = 0; i < 1000; i++) {

            System.out.println(hammingWeight(i));
            System.out.println(hammingWeight2(i));
        }
    }

}
